package com.xiyuan.almighty.service;

import java.util.LinkedList;

/**
 * @创建人 袁继鑫
 * @创建时间 2021-04-08 15:57
 * @版本 1.0
 * @描述
 */
/*
 *  输入的线程,对资源对象Resource中成员变量赋值
 *  一次赋值 张三,男
 *  下一次赋值 lisi,nv
 */
class Input implements Runnable {
    private Resource r;

    public Input(Resource r) {
        this.r = r;
    }

    public void run() {
        int i = 0;
        while (true) {
            synchronized (r) {       // r为了是同一个锁
                //标记是true,等待 理想状态是赋值一次后,在打印,因此要wait
                if (r.flag) {
                    try {
                        r.wait();
                    } catch (Exception ex) {
                    }
                }
                if (i % 2 == 0) {
                    r.name = "张三";
                    r.sex = "男";
                } else {
                    r.name = "lisi";
                    r.sex = "nv";
                }
                //将对方线程唤醒,标记改为true
                r.flag = true;
                r.notify();
            }
            i++;
        }
    }
}


/*
 *  输出线程,对资源对象Resource中成员变量,输出值
 */
class Output implements Runnable {
    private Resource r;

    public Output(Resource r) {
        this.r = r;
    }

    public void run() {
        while (true) {
            synchronized (r) {
                //判断标记,是false,等待
                if (!r.flag) {
                    try {
                        r.wait();
                    } catch (Exception ex) {
                    }
                }
                System.out.println(r.name + ".." + r.sex);
                //标记改成false,唤醒对方线程
                r.flag = false;
                r.notify();
            }
        }
    }
}

class Resource {
    public String name;
    public String sex;
    public boolean flag = false;

}

/*
 *  开启输入线程和输出线程,实现赋值和打印值
 */
public class ThreadDemo {
    public static void main(String[] args) {
        Resource r = new Resource();

        Input in = new Input(r);
        Output out = new Output(r);

        Thread tin = new Thread(in);
        Thread tout = new Thread(out);

        tin.start();
        tout.start();

        new LinkedList();
    }
}
